import "./profileAnalysis.css";

import Card from "./Card";
import BasicInfo from "./BasicInfo";
import MetricsCard from "./MetricsCard";
import { useState, useEffect, useRef, Suspense } from "react";
import { Radio, Spin } from "antd";
import Case from "./Case";
import DisputeHistory from "./DisputeHistory";
import dynamic from "next/dynamic";
import DisputeRelation from "./DisputeRelation";
import RelationExplore from "@/components/RelationExplore";
import { useParams, useSearchParams } from "next/navigation";
import { useSuspenseQuery, useQuery } from "@tanstack/react-query";
import { apiClient } from "@/lib/apiClient";
import { arrayHelper } from "@/utils/common";

const Chart = dynamic(() => import("./Chart"), { ssr: false });

function useBasicInfoQuery({ id }) {
  const query = useSuspenseQuery({
    queryKey: ["basic_info", id],
    queryFn: async () => {
      // TODO 500 code handle

      try {
        const data = await apiClient
          .post(`portraitAnalysis/citizenInfo`, {
            json: {
              idCard: id,
            },
          })
          .json();

        return data;
      } catch (error) {
        return { code: "0000000" };
      }
    },
  });

  return [query.data, query];
}

function useDisputeStatisticsQuery({ id }) {
  const query = useSuspenseQuery({
    queryKey: ["dispute_statistics_try_2", id, "try_too"],
    queryFn: async () => {
      try {
        const data = await apiClient
          .post(`portraitAnalysis/disputeStatistics`, {
            json: {
              idCard: id,
            },
          })
          .json();

        return data;
      } catch (error) {
        return { code: "0000000" };
      }
    },
  });

  return [query.data, query];
}

function useDictQuery() {
  const query = useSuspenseQuery({
    queryKey: ["dict"],
    queryFn: async () => {
      try {
        const data = await apiClient.post(`dict`).json();
        return data;
      } catch (error) {
        return { code: "0000000" };
      }
    },
  });

  return [query.data, query];
}

function useDisputeHistoryQuery({ id, statisticsType, associationType }) {
  const query = useSuspenseQuery({
    queryKey: ["dispute_history", id, statisticsType, associationType],
    queryFn: async () => {
      try {
        const data = await apiClient
          .post(`portraitAnalysis/disputeHistory`, {
            json: {
              idCard: id,
              statisticsType,
              associationType,
            },
          })
          .json();

        return data;
      } catch (error) {
        return { code: "00000000" };
      }
    },
  });

  return [query.data, query];
}

function useGraphStatisticsQuey({ id, statisticsType }) {
  const query = useSuspenseQuery({
    queryKey: ["profile_graph_statistics", id, statisticsType],
    queryFn: async () => {
      try {
        const data = await apiClient
          .post(`portraitAnalysis/graphStatistics`, {
            json: {
              idCard: id,
              statisticsType,
            },
          })
          .json();

        return data;
      } catch (error) {
        return { code: "0000000" };
      }
    },
  });

  return [query.data, query];
}

function useDisputeRelationQuery({ id, statisticsType }) {
  const query = useSuspenseQuery({
    queryKey: ["profile_dispute_relation", id, statisticsType],
    queryFn: async () => {
      try {
        const data = await apiClient
          .post(`portraitAnalysis/disputeRelation`, {
            json: {
              idCard: id,
              statisticsType,
            },
          })
          .json();

        return data;
      } catch (error) {
        return { code: "00000000000" };
      }
    },
  });

  return [query.data, query];
}

function Loading() {
  return (
    <div className="grid h-[70%] place-content-center">
      <Spin size="large" />
    </div>
  );
}

function BasicInfoContainer() {
  const params = useParams();
  const [result] = useBasicInfoQuery({ id: params?.id });

  let data = {};

  if (result.code === 200) {
    data = {
      name: result.data?.citizenInfo?.name,
      gender: result.data?.citizenInfo?.gender,
      age: result.data?.citizenInfo?.age,
      place: result.data?.citizenInfo?.registeredResidenceAddress,
      idNumber: result.data?.citizenInfo?.idCard,
      avatarUrl: result.data?.citizenInfo?.avatarUrl,
      phoneList: arrayHelper(result.data?.phoneList)
        .slice(0, 3)
        .map((item) => {
          return {
            tel: item?.phone,
            dispute: item?.count,
          };
        }),
      address: {
        placeOfRegion: result.data?.citizenInfo?.registeredResidenceAddress,
        residenceAddress: result.data?.citizenInfo?.currentAddress,
      },
      tagList: arrayHelper(result.data?.tagList).map((item) => {
        return {
          name: item?.tagName,
          isHightLight: item?.highlight,
        };
      }),
      wordCloudList: arrayHelper(result.data?.disputeWordList).map((item) => {
        return {
          name: item?.name,
          value: item?.count,
        };
      }),
    };
  }

  return <BasicInfo {...data} />;
}

function disputeHistoryListHelper(result) {
  if (result.code === 200) {
    return arrayHelper(result.data)
      .map((item) => {
        if (item?.disputeSource === "110警情") {
          return {
            type: "police_case",
            date: item?.alarmTime,
            title: item?.disputeType,
            association: {
              // TODO
              value: item?.associationType,
              inputPhoneNumber: item?.associationValue,
              inputId: item?.associationValue,
              id: item?.associationValue,
              relation: item?.associationValue,
              name: item?.associationValue,
            },
            content: item?.alarmContent,
            feedback: item?.policeResponse,
            policeCaseNumber: item?.disputeId,
            numberCallToPolice: item?.alarmPhoneNumber,
            jurisdiction: item?.jurisdictionUnit,
            disputeType: item?.alarmCategory,
            disputeSubtype: item?.alarmSubcategory,
            feedbackUnit: item?.feedbackUnit,
            idOfCallToPolice: item?.alarmPersonIdCard,
            casePlace: item?.caseAddress,
            caseLevel: item?.policeLevel,
            isCriminalCaseSolved: item?.isSolvedCriminalCase,
            isPublicSecurityCaseFound: item?.isHandlingPublicSecurityCase,
            isDisputeCaseResolved: item?.isResolvingDispute,
            sensitiveCase: item?.sensitiveCase,
            subjectOfCase: item?.caseReason,
          };
        }

        if (item?.disputeSource === "协同办案") {
          return {
            type: "joint_investigation",
            date: item?.alarmTime,
            title: item?.disputeType,
            association: {
              // TODO
              value: item?.associationType,
              inputPhoneNumber: item?.associationValue,
              inputId: item?.associationValue,
              id: item?.associationValue,
              relation: item?.associationValue,
              name: item?.associationValue,
            },
            content: item?.briefCaseDescription,
            policeContent: item?.policeContent,
            caseStatus: item?.caseStatus,
            caseCode: item?.disputeId,
            caseName: item?.caseTitle,
            startTimeOfIncident: item?.crimeStartTime,
            illegalInfo: item?.illegalInformation,
            punishCategory: item?.penaltyType,
            peopleInvolvedCaseCategory: item?.personnelInvolvedCategory,
            crimeSceneDetailAddress: item?.caseLocationDetails,
            currentCoerciveMeasure: item?.currentCompulsoryMeasures,
            illegalAct: item?.illegalAct,
            illegalDegree: item?.illegalDegree,
            caseCharges: item?.involvedCharge,
            prosecutionNumber: item?.involvedCharge,
            prosecuteDecisionDate: item?.prosecutionDecisionTime,
            charges: item?.prosecutionCharge,
            actionCause: item?.caseReason,
          };
        }
      })
      .filter((item) => item !== undefined);
  }

  return [];
}

function DisputeHistoryContainer({ statisticType, associationType, dict }) {
  const params = useParams();

  const selectedStatisticType = ((statisticType, dict) => {
    return arrayHelper(dict.statisticsTypeList).find((item) => {
      if (statisticType === "database") {
        return item?.name === "纠纷总数";
      }

      if (statisticType === "police") {
        return item?.name === "警情数量";
      }

      if (statisticType === "case") {
        return item?.name === "案件数量";
      }

      if (statisticType === "risk") {
        return item?.name === "高危纠纷";
      }

      return false;
    });
  })(statisticType, dict);

  const selectedAssociationType = ((associationType, dict) => {
    return arrayHelper(dict.associationTypeList).find((item) => {
      if (associationType === "all") {
        return item?.name === "所有";
      }

      if (associationType === "id") {
        return item?.name === "身份证关联";
      }

      if (associationType === "cell_phone") {
        return item?.name === "手机号关联";
      }

      if (associationType === "association") {
        return item?.name === "关系关联";
      }

      return false;
    });
  })(associationType, dict);

  const [result] = useDisputeHistoryQuery({
    id: params?.id,
    statisticsType: selectedStatisticType?.value,
    associationType: selectedAssociationType?.value,
  });

  const disputeHistoryList = disputeHistoryListHelper(result);

  return <DisputeHistory list={disputeHistoryList} />;
}

function GraphStatisticsContainer({ statisticType, dict, chartHeight }) {
  const params = useParams();
  const selectedStatisticType = ((statisticType, dict) => {
    return arrayHelper(dict.statisticsTypeList).find((item) => {
      if (statisticType === "database") {
        return item?.name === "纠纷总数";
      }

      if (statisticType === "police") {
        return item?.name === "警情数量";
      }

      if (statisticType === "case") {
        return item?.name === "案件数量";
      }

      if (statisticType === "risk") {
        return item?.name === "高危纠纷";
      }

      return false;
    });
  })(statisticType, dict);

  const [result] = useGraphStatisticsQuey({
    id: params?.id,
    statisticsType: selectedStatisticType?.value,
  });

  const entityList = ((result) => {
    if (result.code === 200) {
      if (result.data?.entity && Object.keys(result.data?.entity).length > 0) {
        return Object.entries(result.data?.entity).map(([key, value]) => {
          return {
            name: key,
            value,
          };
        });
      }
    }

    return [];
  })(result);

  const relationList = ((result) => {
    if (result.code === 200) {
      if (
        result.data?.relation &&
        Object.keys(result.data?.relation).length > 0
      ) {
        return Object.entries(result.data?.relation).map(([key, value]) => {
          return {
            name: key,
            value,
          };
        });
      }
    }

    return [];
  })(result);

  return (
    <div className="flex p-1">
      <div className="w-full border-r border-gray-300 pr-2">
        <Chart
          title="纠纷实体数量分布"
          list={entityList}
          height={chartHeight}
        />
      </div>
      <div className="w-full pl-2">
        <Chart
          title="纠纷关系数量分布"
          list={relationList}
          height={chartHeight}
        />
      </div>
    </div>
  );
}

function DisputeRelationWrapper({ statisticType, dict }) {
  const params = useParams();
  const searchParams = useSearchParams();
  const selectedStatisticType = ((statisticType, dict) => {
    return arrayHelper(dict.statisticsTypeList).find((item) => {
      if (statisticType === "database") {
        return item?.name === "纠纷总数";
      }

      if (statisticType === "police") {
        return item?.name === "警情数量";
      }

      if (statisticType === "case") {
        return item?.name === "案件数量";
      }

      if (statisticType === "risk") {
        return item?.name === "高危纠纷";
      }

      return false;
    });
  })(statisticType, dict);

  const { data, status } = useQuery({
    queryKey: [
      "analysis_dispute_relation",
      params?.id,
      selectedStatisticType?.value,
    ],
    queryFn: async () => {
      const data = await apiClient
        .post(`portraitAnalysis/disputeRelation`, {
          json: {
            idCard: params?.id,
            statisticsType: selectedStatisticType?.value,
          },
        })
        .json();

      return data;
    },
    enabled: !!params?.id && !!selectedStatisticType?.value,
    select: (result) => {
      if (result.code === 200) {
        return arrayHelper(result.data).map((item) => {
          return {
            name: item?.name,
            url: item?.idCard,
            avatarUrl: item?.avatarUrl,
            disputeRelation: arrayHelper(item?.relationshipList).join(),
            disputeCount: item?.disputeTotalCount,
            relationCount: item?.personDisputeCount,
            id: item?.idCard,
          };
        });
      }

      return [];
    },
  });

  if (status === "pending") {
    return <Loading />;
  }

  if (status === "error") {
    return null;
  }

  if (status === "success") {
    return <DisputeRelation name={searchParams.get("name")} list={data} />;
  }
}

function DisputeStatisticsContainer() {
  const params = useParams();
  const searchParams = useSearchParams();
  const [result] = useDisputeStatisticsQuery({ id: params?.id });
  const [dictResult] = useDictQuery();

  const dict = ((result) => {
    if (result.code === 200) {
      return result.data;
    }

    return {};
  })(dictResult);

  let disputeTotalCount;
  let police110Count;
  let collaborativeCaseCount;
  let highRiskCount;

  if (result.code === 200) {
    disputeTotalCount = result.data?.disputeTotalCount;
    police110Count = result.data?.police110Count;
    collaborativeCaseCount = result.data?.collaborativeCaseCount;
    highRiskCount = result.data?.highRiskCount;
  }

  const [chartHeight, setChartHeight] = useState(() => 250);
  const historyContainerRef = useRef();

  useEffect(() => {
    setChartHeight(() => (historyContainerRef.current.offsetWidth - 58) * 0.4);
  }, []);

  const [metricsType, setMetricsType] = useState(() => "database");
  const [isDatabaseClick, setIsDatabaseClick] = useState(() => true);
  const [isPoliceClick, setIsPoliceClick] = useState(() => false);
  const [isCaseClick, setIsCaseClick] = useState(() => false);
  const [isRiskClick, setIsRiskClick] = useState(() => false);

  const handleClickMetricsCard = (type) => {
    switch (type) {
      case "database":
        setMetricsType(() => type);
        setIsDatabaseClick(() => true);
        setIsPoliceClick(() => false);
        setIsCaseClick(() => false);
        setIsRiskClick(() => false);
        return;
      case "police":
        setMetricsType(() => type);
        setIsDatabaseClick(() => false);
        setIsPoliceClick(() => true);
        setIsCaseClick(() => false);
        setIsRiskClick(() => false);
        return;
      case "case":
        setMetricsType(() => type);
        setIsDatabaseClick(() => false);
        setIsPoliceClick(() => false);
        setIsCaseClick(() => true);
        setIsRiskClick(() => false);
        return;
      case "risk":
        setMetricsType(() => type);
        setIsDatabaseClick(() => false);
        setIsPoliceClick(() => false);
        setIsCaseClick(() => false);
        setIsRiskClick(() => true);
        return;
    }
  };

  const [disputeHistoryType, setDisputeHistoryType] = useState(() => "all");

  const handleDisputeHistoryRadioClick = (e) => {
    setDisputeHistoryType(() => e.target.value);
  };

  return (
    <>
      <div
        className="dispute-total-container"
        onClick={() => handleClickMetricsCard("database")}
      >
        <MetricsCard
          type="database"
          value={disputeTotalCount}
          isClicked={isDatabaseClick}
        />
      </div>
      <div
        className="police-case-count-container"
        onClick={() => handleClickMetricsCard("police")}
      >
        <MetricsCard
          type="police"
          value={police110Count}
          isClicked={isPoliceClick}
        />
      </div>
      <div
        className="case-count-container"
        onClick={() => handleClickMetricsCard("case")}
      >
        <MetricsCard
          type="case"
          value={collaborativeCaseCount}
          isClicked={isCaseClick}
        />
      </div>
      <div
        className="high-risk-dispute-container"
        onClick={() => handleClickMetricsCard("risk")}
      >
        <MetricsCard
          type="risk"
          value={highRiskCount}
          isClicked={isRiskClick}
        />
      </div>
      <div className="dispute-history-container" ref={historyContainerRef}>
        <Card
          name="纠纷历史"
          rightExtraContent={
            <Radio.Group
              defaultValue="all"
              buttonStyle="solid"
              size="small"
              onChange={handleDisputeHistoryRadioClick}
            >
              <Radio.Button value="all">全部</Radio.Button>
              <Radio.Button value="id">身份证号</Radio.Button>
              <Radio.Button value="cell_phone">手机号</Radio.Button>
              <Radio.Button value="association">关联关系</Radio.Button>
            </Radio.Group>
          }
        >
          <Suspense fallback={<Loading />}>
            <DisputeHistoryContainer
              statisticType={metricsType}
              associationType={disputeHistoryType}
              dict={dict}
            />
          </Suspense>
        </Card>
      </div>
      <div className="graph-statistic-container">
        <Card name="图谱统计">
          <Suspense fallback={<Loading />}>
            <GraphStatisticsContainer
              statisticType={metricsType}
              dict={dict}
              chartHeight={chartHeight}
            />
          </Suspense>
        </Card>
      </div>
      <div className="dispute-relation-container">
        <Card
          name="纠纷关系"
          rightExtraContent={
            <RelationExplore id={params?.id} name={searchParams.get("name")} />
          }
        >
          <DisputeRelationWrapper statisticType={metricsType} dict={dict} />
        </Card>
      </div>
    </>
  );
}

export default function ProfileAnalysis() {
  return (
    <div className="profile-analysis-container">
      <div className="basic-info-container">
        <Card name="基本信息">
          <Suspense fallback={<Loading />}>
            <BasicInfoContainer />
          </Suspense>
        </Card>
      </div>
      <Suspense
        fallback={
          <div className="dispute-statistics-loading">
            <Loading />
          </div>
        }
      >
        <DisputeStatisticsContainer />
      </Suspense>
    </div>
  );
}
